import Koa from 'koa'
import axios from 'axios'
import prisma from '../../prisma/client'
import jwt from 'jsonwebtoken'

const jwtSecret = 'fighting'

class CommonController {
  appId: string
  appSecret: string
  constructor() {
    this.appId = 'wx16e826ca83902ec1'
    this.appSecret = '1c5a350c8615d09108fcc7f8a376d73d'
  }

  async login(ctx: Koa.Context) {
    const code = ctx.request.body.code as string
    const openId = await this.wxAuth(code)
    console.log('openId', openId)
    if (openId) {
      const user = await prisma.user.findUnique({
        include: {
          department: true
        },
        where: {
          openId: openId
        }
      })
      // 判断是否是新用户
      console.log(user)

      if (user) {
        const token = jwt.sign({ id: user?.id }, jwtSecret, { expiresIn: '366d' })
        // 老用户返回信息和token
        ctx.success({ user, token: token, isNew: false }, '成功')
      } else {
        // 新用户
        // 创建
        const newUser = await prisma.user.create({
          data: {
            openId,
            nickname: `用户${openId.slice(0, 5)}`
          }
        })

        const token = jwt.sign({ id: newUser?.id }, jwtSecret, { expiresIn: '366d' })
        ctx.success({ user: newUser, token: token, isNew: true }, '成功')
      }
    } else {
      ctx.fail('微信授权有误，请重试', 505)
    }
  }
  // 更新
  async updateUser(ctx: Koa.Context) {
    const body = ctx.request.body
    console.log(body)

    const token = ctx.request.headers['auth-token'] as string
    const info = jwt.verify(token, jwtSecret) as jwt.JwtPayload
    const currentTime = Date.now() / 1000 // JWT中的exp（过期时间）通常是以秒为单位表示的
    if (info.exp! < currentTime) {
      ctx.fail('token已过期', 500)
    } else {
      await prisma.user.update({
        where: {
          id: info.id
        },
        data: body
      })
      // console.log(res)
      ctx.success(true, '更新成功')
    }
  }

  async wxAuth(loginCode: string): Promise<string> {
    try {
      const {
        data: { openid, session_key }
      } = await axios.get(
        `https://api.weixin.qq.com/sns/jscode2session?appid=${this.appId}&secret=${this.appSecret}&js_code=${loginCode}&grant_type=authorization_code`
      )
      // console.log(data)
      return openid
    } catch (error) {
      console.log(error)
      return ''
    }
  }
  insertUser() {}
  findUser() {}

  async getDepartmentList(ctx: Koa.Context) {
    const data = await prisma.department.findMany()
    // console.log(data)
    ctx.success(data, '成功')
  }
}

export default CommonController
